import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:qilo/core/constants/app_icons.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:video_thumbnail/video_thumbnail.dart';
import 'package:path_provider/path_provider.dart';
import 'package:provider/provider.dart';
import '../../../core/models/hot_item.dart';
import '../../../core/providers/hot_item_provider.dart';
import '../../../core/providers/global_state_coordinator.dart';
import '../../../core/utils/app_utils.dart';
import '../../../core/routes/navigation_helper.dart';

class MusicCreationSharePage extends StatefulWidget {
  const MusicCreationSharePage({super.key});

  @override
  State<MusicCreationSharePage> createState() => _MusicCreationSharePageState();
}

class _MusicCreationSharePageState extends State<MusicCreationSharePage> {
  final TextEditingController _titleController = TextEditingController();
  final TextEditingController _descriptionController = TextEditingController();

  File? _selectedMusicFile;
  File? _videoPreviewFile;
  HotItemType? _contentType;
  bool _isProcessing = false;
  AssetEntity? _selectedAsset;

  @override
  void dispose() {
    _titleController.dispose();
    _descriptionController.dispose();
    super.dispose();
  }

  Future<void> _selectMusicContent() async {
    try {
      final List<AssetEntity>? assets = await AssetPicker.pickAssets(
        context,
        pickerConfig: AssetPickerConfig(
          maxAssets: 1,
          requestType: RequestType.common,
          specialPickerType: SpecialPickerType.noPreview,
          textDelegate: const AssetPickerTextDelegate(),
        ),
      );

      if (assets != null && assets.isNotEmpty) {
        final asset = assets.first;
        _selectedAsset = asset;

        setState(() {
          _isProcessing = true;
        });

        // Get file
        final file = await asset.file;
        if (file != null) {
          _selectedMusicFile = file;

          // Set content type
          if (asset.type == AssetType.image) {
            _contentType = HotItemType.image;
          } else if (asset.type == AssetType.video) {
            _contentType = HotItemType.video;
            // Generate video thumbnail
            await _createVideoPreview();
          }
        }

        setState(() {
          _isProcessing = false;
        });
      }
    } catch (e) {
      setState(() {
        _isProcessing = false;
      });
      if (mounted) {
        AppUtils.showError(context, 'Failed to select file: $e');
      }
    }
  }

  Future<void> _createVideoPreview() async {
    if (_selectedMusicFile == null || _contentType != HotItemType.video) return;

    try {
      final thumbnailPath = await VideoThumbnail.thumbnailFile(
        video: _selectedMusicFile!.path,
        thumbnailPath: (await getTemporaryDirectory()).path,
        imageFormat: ImageFormat.JPEG,
        quality: 75,
      );

      if (thumbnailPath != null) {
        _videoPreviewFile = File(thumbnailPath);
      }
    } catch (e) {
      print('Failed to generate thumbnail: $e');
    }
  }

  Future<String> _copyFileToLocal(File file, String fileName) async {
    try {
      final appDir = await getApplicationDocumentsDirectory();
      final localDir = Directory('${appDir.path}/uploads');
      if (!await localDir.exists()) {
        await localDir.create(recursive: true);
      }

      final localFile = File('${localDir.path}/$fileName');
      await file.copy(localFile.path);
      return localFile.path;
    } catch (e) {
      throw Exception('复制文件失败: $e');
    }
  }

  Future<void> _shareMusicalCreation() async {
    // 检查用户是否登录
    final globalStateCoordinator = context.read<GlobalStateCoordinator>();
    if (!globalStateCoordinator.isLoggedIn) {
      AppUtils.showLoginRequired(
        context,
        message: 'Please login to publish your creation',
        title: 'Login Required',
        onLogin: () {
          NavigationHelper.goToLogin();
        },
      );
      return;
    }

    if (_selectedMusicFile == null || _titleController.text.trim().isEmpty) {
      AppUtils.showWarning(context, 'Please select a file and enter a title');
      return;
    }

    AppUtils.showLoading(context, message: 'Publishing...');

    try {
      // Copy main file to local storage
      final timestamp = DateTime.now().millisecondsSinceEpoch;
      final extension = _selectedMusicFile!.path.split('.').last;
      final fileName = 'music_creation_${timestamp}.$extension';
      final localPath = await _copyFileToLocal(_selectedMusicFile!, fileName);

      // Copy thumbnail if exists
      String? thumbnailPath;
      if (_videoPreviewFile != null) {
        final thumbnailFileName = 'preview_${timestamp}.jpg';
        thumbnailPath = await _copyFileToLocal(
          _videoPreviewFile!,
          thumbnailFileName,
        );
      }

      // Create HotItem with real user ID
      final currentUser = globalStateCoordinator.currentUser!;
      final hotItem = HotItem(
        id: 'user_$timestamp',
        publisherId: currentUser.id,
        type: _contentType!,
        title: _titleController.text.trim(),
        description:
            _descriptionController.text.trim().isEmpty
                ? 'Share Your Performance Recordings, Practice Results, Or Original Music'
                : _descriptionController.text.trim(),
        commentCount: 0,
        likeCount: 0,
        resourceUrl: localPath,
        thumbnailUrl: thumbnailPath,
        isRecommended: false,
      );

      // Add to provider
      if (mounted) {
        context.read<HotItemProvider>().addItem(hotItem);

        await Future.delayed(const Duration(seconds: 2));

        if (mounted) {
          AppUtils.hideLoading(context);
          AppUtils.showSuccess(context, 'Published successfully!');

          Navigator.pop(context);
        }
      }
    } catch (e) {
      if (mounted) {
        AppUtils.hideLoading(context);
        AppUtils.showError(context, 'Failed to publish: $e');
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/my-bg.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: Scaffold(
          backgroundColor: Colors.transparent,
          appBar: AppBar(
            backgroundColor: Colors.transparent,
            elevation: 0,
            leading: IconButton(
              icon: Icon(
                Icons.arrow_back_ios,
                color: Colors.white,
                size: 22.sp,
              ),
              onPressed: () => Navigator.pop(context),
            ),
            title: Text(
              'Post',
              style: TextStyle(
                color: Colors.white,
                fontSize: 22.sp,
                fontWeight: FontWeight.w600,
              ),
            ),
            centerTitle: true,
          ),
          body: SingleChildScrollView(
            child: Padding(
              padding: EdgeInsets.all(16.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // Title input
                  TextField(
                    textInputAction: TextInputAction.done,
                    controller: _titleController,
                    style: TextStyle(color: Colors.white, fontSize: 16.sp),
                    decoration: InputDecoration(
                      hintText: 'Please Enter A Title',
                      hintStyle: TextStyle(
                        color: Colors.white.withOpacity(0.6),
                        fontSize: 16.sp,
                      ),
                      border: InputBorder.none,
                      enabledBorder: UnderlineInputBorder(
                        borderSide: BorderSide(
                          color: Colors.white.withOpacity(0.3),
                        ),
                      ),
                      focusedBorder: const UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.white),
                      ),
                    ),
                  ),

                  SizedBox(height: 20.h),

                  // Description input
                  TextField(
                    controller: _descriptionController,
                    textInputAction: TextInputAction.done,
                    style: TextStyle(color: Colors.white, fontSize: 14.sp),
                    maxLines: 3,
                    decoration: InputDecoration(
                      hintText:
                          'Share Your Performance Recordings, Practice Results, Or Original Music',
                      hintStyle: TextStyle(
                        color: Colors.white.withAlpha(150),
                        fontSize: 14.sp,
                      ),
                      border: InputBorder.none,
                    ),
                  ),

                  SizedBox(height: 40.h),

                  // Media selection area
                  GestureDetector(
                    onTap: _isProcessing ? null : _selectMusicContent,
                    child: CustomPaint(
                      painter: DashedBorderPainter(
                        color: Colors.white.withAlpha(130),
                        strokeWidth: 2,
                        dashWidth: 8,
                        dashSpace: 4,
                        borderRadius: 8.r,
                      ),
                      child: SizedBox(
                        width: 120.w,
                        height: 120.w,
                        child:
                            _isProcessing
                                ? const Center(
                                  child: CircularProgressIndicator(
                                    color: Colors.white,
                                  ),
                                )
                                : _selectedMusicFile == null
                                ? Icon(
                                  Icons.add,
                                  color: Colors.white.withOpacity(0.7),
                                  size: 40.sp,
                                )
                                : ClipRRect(
                                  borderRadius: BorderRadius.circular(6.r),
                                  child: _buildPreview(),
                                ),
                      ),
                    ),
                  ),

                  SizedBox(height: 200.h),

                  // Release button
                  SizedBox(
                    width: double.infinity,
                    height: 50.h,
                    child: ElevatedButton(
                      onPressed: _isProcessing ? null : _shareMusicalCreation,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: const Color(0xFFD2756B),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(25.r),
                        ),
                      ),
                      child:
                          _isProcessing
                              ? const CircularProgressIndicator(
                                color: Colors.white,
                              )
                              : Text(
                                'Release',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 16.sp,
                                  fontWeight: FontWeight.w600,
                                ),
                              ),
                    ),
                  ),

                  SizedBox(height: 60.h),

                  // EULA text
                  Center(
                    child: GestureDetector(
                      onTap: () {
                        AppUtils.openUrl(
                          'https://www.freeprivacypolicy.com/live/82e54f5c-a3a3-4bc8-a08a-0da176425cf4',
                        );
                      },
                      child: Text(
                        'EULA',
                        style: TextStyle(
                          color: Colors.white.withValues(alpha: 0.80),
                          fontSize: 15.sp,
                          fontWeight: FontWeight.w400,
                          decoration: TextDecoration.underline,
                          decorationColor: Colors.white.withValues(alpha: 0.80),
                        ),
                      ),
                    ),
                  ),
                  SizedBox(height: 36.h),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildPreview() {
    if (_selectedMusicFile == null) return const SizedBox();

    if (_contentType == HotItemType.image) {
      return Image.file(
        _selectedMusicFile!,
        fit: BoxFit.cover,
        width: double.infinity,
        height: double.infinity,
      );
    } else if (_contentType == HotItemType.video) {
      return Stack(
        children: [
          if (_videoPreviewFile != null)
            Image.file(
              _videoPreviewFile!,
              fit: BoxFit.cover,
              width: double.infinity,
              height: double.infinity,
            )
          else
            Container(
              color: Colors.black26,
              child: Icon(
                Icons.video_library,
                color: Colors.white,
                size: 30.sp,
              ),
            ),
          Positioned(
            top: 0,
            bottom: 0,
            right: 0,
            left: 0,

            child: Icon(MyIcons.iconPlayFill, color: Colors.white, size: 22.sp),
          ),
        ],
      );
    }

    return const SizedBox();
  }
}

/// Custom painter for dashed border
class DashedBorderPainter extends CustomPainter {
  final Color color;
  final double strokeWidth;
  final double dashWidth;
  final double dashSpace;
  final double borderRadius;

  DashedBorderPainter({
    required this.color,
    required this.strokeWidth,
    required this.dashWidth,
    required this.dashSpace,
    required this.borderRadius,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final paint =
        Paint()
          ..color = color
          ..strokeWidth = strokeWidth
          ..style = PaintingStyle.stroke;

    final path =
        Path()..addRRect(
          RRect.fromRectAndRadius(
            Rect.fromLTWH(0, 0, size.width, size.height),
            Radius.circular(borderRadius),
          ),
        );

    _drawDashedPath(canvas, path, paint);
  }

  void _drawDashedPath(Canvas canvas, Path path, Paint paint) {
    final pathMetrics = path.computeMetrics();
    for (final pathMetric in pathMetrics) {
      double distance = 0.0;
      while (distance < pathMetric.length) {
        final segment = pathMetric.extractPath(distance, distance + dashWidth);
        canvas.drawPath(segment, paint);
        distance += dashWidth + dashSpace;
      }
    }
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => false;
}
